import json
import os

from PyQt5.QtCore import QStringListModel, QModelIndex, Qt
from PyQt5.QtWidgets import QHBoxLayout, QVBoxLayout, QWidget, QPushButton, \
    QFormLayout, QLineEdit, QMessageBox

from model.DbInfo import DbInfo
from ui.gbq.ui.BaseDiaWidget import BaseDiaWidget
from ui.DbBrowser import DbBrowser
from ui.gbq.ui.gqlistview import GQListView
from util import contants


class SessionMangerWindow(BaseDiaWidget):
    edted = False
    selected = False
    notCancel = True

    def __init__(self, parent=None):
        super(SessionMangerWindow, self).__init__(parent)
        self.dbInfoList = []
        self.dbListItem = []
        self.dbInfo = DbInfo()
        self.initUI()
        self.initDbInfos()

    def initDbInfos(self):
        try:
            with open(contants.path + os.sep + "config" + os.sep + "dblist", "r", encoding='UTF-8') as dbf:
                self.dbInfoList = json.load(dbf)
            i = 0
            for info in self.dbInfoList:
                dbInfo = DbInfo()
                dbInfo.__dict__ = info
                self.dbInfoList[i] = dbInfo
                self.dbListItem.append(dbInfo.name)
                self.slm.setStringList(self.dbListItem)
                i += 1
            # self.dbList.clicked.emit(self.slm.index(0))
            self.dbList.setCurrentIndex(self.slm.index(0))
        except BaseException as e:
            print(e)

    def initUI(self):
        # 设置窗口标题
        self.setWindowTitle("会话管理器")

        #         尺寸
        self.resize(800, 400)

        self.mainWindows = QHBoxLayout()
        self.setLayout(self.mainWindows)

        self.leftWindows = QVBoxLayout()
        self.rightWindows = QVBoxLayout()

        self.leftWidget = QWidget()
        self.rightWidget = QWidget()
        self.mainWindows.addWidget(self.leftWidget)
        self.mainWindows.addWidget(self.rightWidget)
        self.leftWidget.setFixedWidth(200)
        self.leftWidget.setLayout(self.leftWindows)
        self.rightWidget.setLayout(self.rightWindows)
        self.dbList = GQListView()
        # self.dbList.setEditTriggers(QListView.NoEditTriggers)
        # 实例化列表模型，添加数据
        self.slm = QStringListModel(self.dbListItem)
        self.dbList.setModel(self.slm)
        self.leftWindows.addWidget(self.dbList)

        self.dbBtnLayout = QHBoxLayout()
        self.newBtn = QPushButton("新建")
        self.saveBtn = QPushButton("保存")
        self.delBtn = QPushButton("删除")
        self.dbBtnLayout.addWidget(self.newBtn)
        self.dbBtnLayout.addWidget(self.saveBtn)
        self.dbBtnLayout.addWidget(self.delBtn)
        self.leftWindows.addLayout(self.dbBtnLayout)

        self.dbInfoForm = QFormLayout()
        self.hostLine = QLineEdit()
        self.portLine = QLineEdit()
        self.pwdLine = QLineEdit()
        self.userNameLine = QLineEdit()
        self.pwdLine.setEchoMode(QLineEdit.Password)
        self.dbInfoForm.addRow("主机名/IP", self.hostLine)
        self.dbInfoForm.addRow("端口", self.portLine)
        self.dbInfoForm.addRow("用户名", self.userNameLine)
        self.dbInfoForm.addRow("密码", self.pwdLine)

        self.rightWindows.addLayout(self.dbInfoForm)

        self.openBtn = QPushButton("打开")
        self.cnacelBtn = QPushButton("取消")
        self.openBtn.setFixedWidth(80)
        self.cnacelBtn.setFixedWidth(80)
        self.operationBtnLayout = QHBoxLayout()
        self.operationBtnLayout.addWidget(self.openBtn)
        self.operationBtnLayout.addWidget(self.cnacelBtn)
        self.operationBtnLayout.setAlignment(Qt.AlignRight)

        self.rightWindows.addLayout(self.operationBtnLayout)

        self.dbList.clicked.connect(self.dbClicked)
        self.newBtn.clicked.connect(self.newDb)
        self.saveBtn.clicked.connect(self.saveClicked)
        self.delBtn.clicked.connect(self.delDb)
        self.openBtn.clicked.connect(self.openDb)
        self.cnacelBtn.clicked.connect(self.cancel)
        self.hostLine.textChanged.connect(self.textChanged)
        self.pwdLine.textChanged.connect(self.textChanged)
        self.portLine.textChanged.connect(self.textChanged)
        self.userNameLine.textChanged.connect(self.textChanged)
        self.dbList.dataChanged = self.dataChanged
        self.dbList.currentChanged = self.currentChanged

    def showDialog(self):
        return QMessageBox.question(self,
                                    "确认",
                                    "确定修改?",
                                    QMessageBox.Yes | QMessageBox.No | QMessageBox.Cancel)

    def currentChanged(self, index: QModelIndex, indexPre: QModelIndex):
        self.setDbInfo(index.row())

    #     try:
    #         print("selected " + str(index.row()))
    #         print("pre " + str(indexPre.row()))
    #     except BaseException as e:
    #         print(e)
    #     if indexPre.row() != -1 and self.edted:
    #         if self.notCancel:
    #             reply = self.showDialog()
    #             if reply == QMessageBox.Yes:
    #                 self.notCancel = True
    #                 self.edted = False
    #                 # self.dbList.clicked.emit(self.slm.index(index.row()))
    #             elif reply == QMessageBox.No:
    #                 self.notCancel = True
    #                 self.edted = False
    #                 # self.dbList.clicked.emit(self.slm.index(index.row()))
    #             elif reply == QMessageBox.Cancel:
    #                 self.notCancel = False
    #                 # self.dbList.clicked.emit(self.slm.index(indexPre.row()))
    #                 # self.dbList.setCurrentIndex(self.slm.index(indexPre.row()))
    #                 return
    #         else:
    #             print("set not cancel")
    #             self.notCancel = True
    #     if self.notCancel:
    #         print("setDbInfo")
    #         self.setDbInfo(index.row())

    def textChanged(self, lineStr):
        if self.sender().hasFocus():
            self.edted = True
            self.notCancel = True

    def dataChanged(self, index: QModelIndex, indexpre: QModelIndex, roles, p_int=None, *args, **kwargs):
        print(index.data())
        self.dbListItem[index.row()] = index.data()
        self.dbInfoList[index.row()].name = index.data()

    def initDbInfo(self):
        try:
            self.hostLine.setText(self.dbInfo.host)
            self.pwdLine.setText(self.dbInfo.pwd)
            self.portLine.setText(str(self.dbInfo.port))
            self.userNameLine.setText(self.dbInfo.userName)
        except:
            pass

    # 点击数据库列表
    def dbClicked(self, qModelIndex: QModelIndex):
        pass

    def setDbInfo(self, index):
        self.dbInfo = self.dbInfoList[index]
        self.initDbInfo()

    # 新建
    def newDb(self):
        newDbInfo = DbInfo()
        self.dbInfoList.append(newDbInfo)
        self.dbListItem.append(newDbInfo.name)
        self.slm.setStringList(self.dbListItem)
        self.dbList.clicked.emit(self.slm.index(len(self.dbListItem) - 1))
        self.dbList.setCurrentIndex(self.slm.index(len(self.dbListItem) - 1))
        self.dbList.edit(self.slm.index(len(self.dbListItem) - 1))

    def saveClicked(self):
        self.dbInfo.host = self.hostLine.text()
        self.dbInfo.pwd = self.pwdLine.text()
        self.dbInfo.port = int(self.portLine.text())
        self.dbInfo.userName = self.userNameLine.text()
        self.dbInfoList[self.dbList.currentIndex().row()] = self.dbInfo
        self.saveDbInfoList()

    # 保存
    def saveDbInfoList(self):
        dbInfoListDict = [x.__dict__ for x in self.dbInfoList]
        with open(contants.path + os.sep + "config" + os.sep + "dblist", "w", encoding='UTF-8') as f:
            json.dump(dbInfoListDict, f, ensure_ascii=False, indent=2)

    # 删除
    def delDb(self):
        try:
            index = self.dbList.currentIndex().row()
            del self.dbInfoList[index]
            del self.dbListItem[index]
            self.slm.setStringList(self.dbListItem)
            realIndex = index if index < len(self.dbListItem) else len(self.dbListItem) - 1
            self.dbList.clicked.emit(self.slm.index(realIndex))
            self.dbList.setCurrentIndex(self.slm.index(realIndex))
        except:
            pass

    # 打开
    def openDb(self):
        try:
            self.dbBrowser = DbBrowser(self.dbInfo)
            self.dbBrowser.show()
            self.close()
        except BaseException as e:
            print(e)
            msg_box = QMessageBox(QMessageBox.Warning, '警告', str(e))
            msg_box.show()

    # 取消
    def cancel(self):
        self.close()
